#include <dbentity/T_XG_FILE.h>
#include <dbentity/T_XG_NOTE.h>
#include <webx/route.h>

class NoteFile : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(NoteFile)

int NoteFile::process()
{
	param_string(flag);
	param_string(dbid);
	param_name_string(id);

	auto process = [&](sp<QueryResult> rs){
		if (!rs) return simpleResponse(XG_SYSERR);

		sp<RowData> row = rs->next();
	
		if (!row) return simpleResponse(XG_NOTFOUND);

		DateTime utime;
		SmartBuffer data = row->getBinary(1);

		if (data.size() > 4096 && row->getDateTime(utime, 2))
		{
			char etag[64];
			string version = request->getHeadValue("If-None-Match");

			sprintf(etag, "%ld:%d", utime.getTime(), data.size());
			response->setHeadValue("ETag", etag);

			if (version == etag)
			{
				response->setErrorString("Not Modified");
				response->setErrorCode(304);

				return XG_OK;
			}
		}

		createFile(data.size());
		
		response->setContentType(row->getString(0));

		return file->write(data.str(), data.size());
	};

	try
	{
		const string& user = checkLogin();

		if (flag == "S" && dbid.empty()) dbid = token->getDataId();

		sp<DBConnect> dbconn = webx::GetDBConnect(dbid);

		if (flag == "S")
		{
			CT_XG_NOTE tab;

			tab.init(dbconn);
			tab.id = id;

			if (!tab.find()) return simpleResponse(XG_SYSERR);

			int res = XG_NOTFOUND;

			if (tab.next() && user == tab.user.val())
			{
				CT_XG_FILE tf;
				SmartBuffer content;

				param_path_string(path);

				path = app->getPath() + path;

				if (stdx::GetFileContent(content, path) <= 0) return simpleResponse(XG_PARAMERR);

				string imme = app->getMimeType(stdx::tolower(path::extname(path)));

				tf.init(dbconn);
				tf.imme = imme;
				tf.type = "NOTE";
				tf.rid = tab.id;
				tf.content = content;
				tf.statetime.update();

				for (int i = 0; i < 5; i++)
				{
					tf.id = DateTime::GetBizId();

					if ((res = tf.insert()) >= 0) break;
				}

				if (res >= 0)
				{
					if (user == "system")
					{
						json["url"] = "/notefile?id=" + tf.id.val();
					}
					else
					{
						json["url"] = "/notefile?id=" + tf.id.val() + "&dbid=" + dbid;
					}
					
					path::remove(path);
				}
 			}
			
			json["code"] = res;
			out << json;
		}
		else
		{
			string sqlcmd = "SELECT b.IMME,b.CONTENT,b.STATETIME FROM T_XG_NOTE a,T_XG_FILE b WHERE a.ID=b.RID AND b.ID=? AND (a.USER=? OR a.LEVEL>2)";

			return process(dbconn->query(sqlcmd, id, user));
		}
	}
	catch(Exception e)
	{
		string sqlcmd = "SELECT b.IMME,b.CONTENT,b.STATETIME FROM T_XG_NOTE a,T_XG_FILE b WHERE a.ID=b.RID AND b.ID=? AND a.LEVEL>2";
		
		return process(webx::GetDBConnect(dbid)->query(sqlcmd, id));
	}

	return XG_OK;
}